import java.util.StringTokenizer;
import java.util.Vector;

class P11005_39643 {

    private static int[] map;

	public static void main(String[] args) {
    	
    	int cases = Integer.parseInt(readLn());
    	
    	for (int k = 0; k < cases; k++) {
    		System.out.println("Case " + (k+1) + ":");
    		process();
    		if (k + 1 < cases) System.out.println();
    	}
    }

    private static void process() {
    	map = new int[36];
    	
    	read(0, readLn());
    	read(9, readLn());
    	read(18, readLn());
    	read(27, readLn());
    	
//    	for (int i : map) {
//    		System.out.println(i);
//    	}
    	
    	int queries = Integer.parseInt(readLn());
    	
    	for (int k = 0; k < queries; k++) {
    		processQuery();
    	}
	}

	private static void processQuery() {
		String query = readLn();
		
		Vector cheapest = new Vector();
		int cheapestValue = Integer.MAX_VALUE;
		
		for (int k = 2; k <= 36; k++) {
			int value = calculateValue(query, k);
			
			if (cheapestValue > value) {
				cheapestValue = value;
				cheapest = new Vector();
				cheapest.addElement(new Integer(k));
			} else if (cheapestValue == value) {
				cheapest.addElement(new Integer(k));
			}
		}
		
		System.out.print("Cheapest base(s) for number " + query + ": ");
		
		StringBuffer sb = new StringBuffer();
		
		int length = cheapest.size();
		
		for (int k = 0; k < length; k++) {
			sb.append(cheapest.elementAt(k) + " "); 
		}
		
		System.out.println(sb.toString().trim());
		
	}

	private static int calculateValue(String query, int radix) {
		String queryInRadix = Integer.toString(Integer.parseInt(query), radix);
		int value = 0;
		
		int length = queryInRadix.length();
		for (int k = 0; k < length; k++) {
			value = value + getValue(queryInRadix.charAt(k));
		}
		return value;
	}

	private static int getValue(char c) {
		if ('0' <= c &&  c <= '9') {
			return map[c-'0'];
		}
		return map[c-'a' + 10];
	}

	private static void read(int i, String string) {
		StringTokenizer st = new StringTokenizer(string);
		
		int length = i + 9;
		for (int k = i; k < length; k++) {
			map[k] = Integer.parseInt(st.nextToken());
		}
	}

	static String readLn() {
        String newLine = System.getProperty("line.separator");
        StringBuffer buffer = new StringBuffer();
        int car = -1;
        try {
            car = System.in.read();
            while ((car > 0) && (car != newLine.charAt(0))) {
                buffer.append((char)car);
                car = System.in.read();
            }
            if (car == newLine.charAt(0))
            System.in.skip(newLine.length() - 1);
        } catch (java.io.IOException e) { return (null);}
        if ((car < 0) && (buffer.length() == 0)) return (null);
        return (buffer.toString()).trim();
    }

}